package com.brkj.test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.widget.*;
import com.brkj.util.view.*;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;
import com.brkj.httpInterface.BaseAjaxParams;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;

import com.brkj.main.R;
import com.brkj.test.model.DS_Exam;
import com.brkj.test.model.DS_Exam_detail_ques;
import com.brkj.test.model.DS_QuesRecord;
import com.brkj.httpInterface.HttpInterface.HIF_GetExamDetail;
import com.brkj.util.ConstAnts;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.Util;
import com.dgl.sdk.util.DBStore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ExamDetailActivity extends BaseActionBarActivity{

	private MyViewPager viewPager;
	private ArrayList<View> views = new ArrayList<View>();
	private ArrayList<QuestionItem> questionViewList = new ArrayList<QuestionItem>();
	private String examPaperID;
	
	private List<DS_Exam_detail_ques> quesList;
    private List<DS_Exam_detail_ques> wrongList = new ArrayList<DS_Exam_detail_ques>();
	
	private TextView doProgress;
	private TextView wrongNum;
	private TextView lastNum;
	
	private int quesHavedoNum = 1;
	private int quesTotalNum = 0;
	private int quesWrongNum = 0;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.test_exam_detail);


        setReturnBtn();

		viewPager = (MyViewPager) findViewById(R.id.viewPager);

		examPaperID = Integer.toString(((DS_Exam)getIntent().getSerializableExtra("exam")).getExamPaperID());
		setActivityTitle(((DS_Exam)getIntent().getSerializableExtra("exam")).getExamPaperName());

        wrongList = DBStore.readAll(DS_Exam_detail_ques.class, ConstAnts.DB_TABLE_WRONGQUES+examPaperID);

        addRightButtonItem("错题收藏夹", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {
                showWrongQuesList();
            }
        });
        addRightButtonItem("跳转试题", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {
                SelectDoDialog dialog = new SelectDoDialog();
                dialog.show();
            }
        });

        setRightBtnBackground(R.drawable.exam_detail_rightbtn_selector);

		doProgress = (TextView) findViewById(R.id.doProgress);
		wrongNum = (TextView) findViewById(R.id.wrongNum);
		lastNum = (TextView) findViewById(R.id.lastNum);
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				quesHavedoNum = arg0 + 1;
				setQuesNum();
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if((questionViewList.size()>0)
					&&(questionViewList.get(arg0)!=null)){
					questionViewList.get(arg0).clearAnswer();
				}
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

        getExamDetail();
	}

	private void getExamDetail() {
        DS_Exam exam = DBStore.read(DS_Exam.class, ConstAnts.DB_TABLE_OFFLINE_QUES_LIST, " ExamPaperID=" + examPaperID);

        if(exam!=null){
            progressDialog.setMessage("正在读取数据...");
            progressDialog.show();

            final Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if((quesList != null) && (quesList.size()>0)){
                        quesTotalNum = quesList.size();
                        showQuestion();
                        if(readHaveDoneQues()!= 0){
                            IfBeginDoDialog dialog = new IfBeginDoDialog();
                            dialog.show();
                        }

                        setQuesNum();

                    }else{
                        showToast("读取数据失败！");
                    }

                    progressDialog.dismiss();
                }
            };

            new Thread(){
                @Override
                public void run() {
                    quesList = DBStore.readAll(DS_Exam_detail_ques.class,
                            ConstAnts.DB_TABLE_OFFLINE_QUES_DETAIL+examPaperID);

                    handler.sendEmptyMessage(0);
                }
            }.start();

            return;
        }



		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetExamDetail.params.ExamPaperID, examPaperID);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetExamDetail.address, params, new MyAjaxCallBack<Object>(this) {

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Exam_detail_ques>>(){}.getType();
				quesList = gson.fromJson((String)t, listType);
				
				if(quesList != null){
					quesTotalNum = quesList.size();
					showQuestion();
					if(readHaveDoneQues()!= 0){
						IfBeginDoDialog dialog = new IfBeginDoDialog();
						dialog.show();
					}
					
					setQuesNum();
				}else{
					showToast("获取问卷失败！");
				}
			}
			
		});
		

	}

	//跳转到上次做题的地方
	protected void jumpToHaveDone() {
		int haveDoneNum;
		FinalDb db = FinalDb.create(this, ConstAnts.BRKJ_DB);
		List<DS_QuesRecord> savedList = db.findAllByWhere(DS_QuesRecord.class, 
				" ExamPaperID=" + examPaperID); 
		
		if((savedList!=null) && (savedList.size()>0)){
			haveDoneNum = savedList.get(0).getHaveDownNum();
			quesWrongNum = savedList.get(0).getWrongNum();
			
			viewPager.setCurrentItem(haveDoneNum);
			wrongNum.setText(quesWrongNum + "");
		}
	}

	protected void showQuestion() {
		for(int i=0; i<quesList.size(); i++){
			QuestionItem questionItem;
			if(i== (quesList.size()-1)){
				questionItem = new QuestionItem(quesList.get(i), true);
			}else{
				questionItem = new QuestionItem(quesList.get(i), false);
			}
			
			questionViewList.add(questionItem);
			
			views.add(questionItem.getView());
		}
		viewPager.setViews(views);
	}
	
	private class QuestionItem{
	
		private View questionItemView;
		private DS_Exam_detail_ques quesItem;
		private boolean isCount = false;
		private boolean isDoWrong = false;
		private boolean isLast = false;
		private Question question;
		private int orig_quesWrongNum;
        private PopupWindow popupWindow;
        private Button popRedoBtn;
        private Button popNextBtn;
        private View popRightView;
        private View popWrongView;
        private TextView popAnswerText;

		public QuestionItem(final DS_Exam_detail_ques quesItem, boolean isLast){
			this.quesItem = quesItem;
			this.isLast = isLast;
			
			orig_quesWrongNum = quesWrongNum;
		}
		
		public View getView(){
			
			question = new Question(ExamDetailActivity.this, quesItem);
			questionItemView = LayoutInflater.from(ExamDetailActivity.this).inflate(R.layout.test_exam_detail_ques_item, null);
			LinearLayout questionView = (LinearLayout) questionItemView.findViewById(R.id.questionView);
			Button submitAnswer = (Button) questionItemView.findViewById(R.id.submitAnswer);
			Button saveToWrongFolder = (Button) questionItemView.findViewById(R.id.saveToWrongFolder);


            initAnswerPopUpWindow();

            String answerStr;
            if(quesItem.getAnswer().equals("true")){
                answerStr =  "正确";
            }else if(quesItem.getAnswer().equals("false")){
                answerStr =  "错误";
            }else{
                answerStr = quesItem.getAnswer();
            }
            popAnswerText.setText(answerStr);

            //判断此题是否已经加入了错题夹
            boolean isSaveToWronglist = false;
            for(DS_Exam_detail_ques wrongques:wrongList){
                if(wrongques.getUTID() == quesItem.getUTID()){
                    isSaveToWronglist = true;
                    break;
                }
            }

            if(isSaveToWronglist){
                saveToWrongFolder.setText("移出错题夹");
                saveToWrongFolder.setTag("del");
            }else{
                saveToWrongFolder.setText("加入错题夹");
                saveToWrongFolder.setTag("add");
            }

			saveToWrongFolder.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(v.getTag().equals("add")){
                        saveWrongQues(quesItem);

                        ((Button) v).setText("移出错题夹");

                        v.setTag("del");
                    }else if (v.getTag().equals("del")){
                        removeWrongQues(quesItem);
                        ((Button) v).setText("加入错题夹");

                        v.setTag("add");
                    }

                }
            });
			
			if(isLast){
                popNextBtn.setText("学习完成");
                popNextBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						finish();
					}
				});
			}else{
                popNextBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						viewPager.goNext();
                        popupWindow.dismiss();
					}
				});
			}
            popRedoBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					clearAnswer();
                    popupWindow.dismiss();
//					quesHavedoNum = orig_quesHavedoNum;
//					quesWrongNum = orig_quesWrongNum;
//					setQuesNum();
//					if(isDoWrong){
//						quesWrongNum--;
//						setQuesNum();
//					}
				}
			});
			

			submitAnswer.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(question.getAnswer().equals("") ||
							(question.getAnswer()== null)){
						showToast("请先做题！");
						return;
					}
					
					//如果后台没有传答案过来！防止崩溃
					if(quesItem.Answer == null){
						showToast("未获取到标准答案！");
						return;
					}

                    popupWindow.showAtLocation(viewPager, Gravity.CENTER, 0, 0);
					
					if(quesItem.getAnswer().toLowerCase().equals(question.getAnswer().toLowerCase())){
//					if(question.getAnswer().contains(quesItem.getAnswer())){
                        popRightView.setVisibility(View.VISIBLE);
                        popWrongView.setVisibility(View.GONE);
						isDoWrong = false;
					}else{
                        popRightView.setVisibility(View.GONE);
                        popWrongView.setVisibility(View.VISIBLE);
						isDoWrong = true;
					};
					
					if(!isCount){
						if(isDoWrong){
							quesWrongNum++;
						}
						
						setQuesNum();
						isCount = true;
					}
					

					
				}
			});
			questionView.addView(question.getView());
			
			
			return questionItemView;
		}

        private void initAnswerPopUpWindow(){

            View popupWindow_view = getLayoutInflater().inflate(
                    R.layout.test_answer_popupwindow, null, false);
            popupWindow = new PopupWindow(popupWindow_view,
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, false);// 鍒涘缓PopupWindow瀹炰緥

            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            // popupWindow.setAnimationStyle(R.style.PopWindowAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0));


            popRedoBtn = (Button) popupWindow_view.findViewById(R.id.redoBtn);
            popNextBtn = (Button) popupWindow_view.findViewById(R.id.nextBtn);
            popRightView = (View) popupWindow_view.findViewById(R.id.rightView);
            popWrongView = (View) popupWindow_view.findViewById(R.id.wrongView);
            popAnswerText = (TextView) popupWindow_view.findViewById(R.id.answerText);

        }

		//清除做题记录
		public void clearAnswer() {
			if(question != null){
				question.clearAnswer();
			}
		}
		
		//保存错题
		private void saveWrongQues(DS_Exam_detail_ques wrongQues){
			DBStore.save(wrongQues, ConstAnts.DB_TABLE_WRONGQUES + examPaperID);
		}

        //删除错题
        private void removeWrongQues(DS_Exam_detail_ques wrongQues){
            DBStore.delete(wrongQues, ConstAnts.DB_TABLE_WRONGQUES + examPaperID);
        }
	}



	private void setQuesNum(){
		doProgress.setText("做题进度："+ quesHavedoNum + "/" + quesTotalNum );
		wrongNum.setText(quesWrongNum+"" );
		lastNum.setText("剩余："+ (quesTotalNum - quesHavedoNum) + "道"); 
	}
	
	public class IfBeginDoDialog {
		protected Button ok;
		protected Button cancle;
		
		protected Dialog dialog;

		public IfBeginDoDialog() {
			dialog = new Dialog(ExamDetailActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.dialog_if_begin_do);

			ok = (Button) dialog.findViewById(R.id.ok);
			cancle = (Button) dialog.findViewById(R.id.cancle);
		
			cancle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			
			ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					jumpToHaveDone();
					dialog.dismiss();
				}
			});
		}
		
		
		public void show(){
			dialog.show();
		}
	}
	
	
	public class SelectDoDialog {
		protected Button ok;
		protected Button cancle;
		protected EditText selectNum;
		protected TextView totalNumView;
		
		protected Dialog dialog;

		public SelectDoDialog() {
			dialog = new Dialog(ExamDetailActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.dialog_select_question);

			ok = (Button) dialog.findViewById(R.id.ok);
			cancle = (Button) dialog.findViewById(R.id.cancle);
			selectNum = (EditText) dialog.findViewById(R.id.selectNum);
			totalNumView = (TextView) dialog.findViewById(R.id.totalNum);
			
			totalNumView.setText("/" + quesTotalNum + "道");
			selectNum.setText(quesHavedoNum + "");
			
			cancle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			
			ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(!WidgetAnim.checkIfEmpty(ExamDetailActivity.this, selectNum)){
						String seectNumText = selectNum.getText().toString();
						if(Util.isNumeric(seectNumText)
								&&(Integer.valueOf(seectNumText)<=quesTotalNum)){
							viewPager.setCurrentItem(Integer.valueOf(seectNumText) -1);
						}else{
							showToast("请输入有效的数字");
						}
						
					};
					dialog.dismiss();
				}
			});
		}
		
		
		public void show(){
			dialog.show();
		}
	}


	@Override
	public void finish() {
		saveHaveDoneQues();
		
		Intent intent = new Intent();
		intent.setAction("com.brkj.examHaveDoneChanged");
		sendBroadcast(intent);
		
		super.finish();
		
		
	}

	private void saveHaveDoneQues() {

		FinalDb db = FinalDb.create(this, ConstAnts.BRKJ_DB);
		List<DS_QuesRecord> savedList = db.findAllByWhere(DS_QuesRecord.class, 
				" ExamPaperID=" + examPaperID); 
		
		if((savedList!=null) && (savedList.size()>0)){
			savedList.get(0).setHaveDownNum(quesHavedoNum-1);
			savedList.get(0).setWrongNum(quesWrongNum);
			db.update(savedList.get(0), 
					" ExamPaperID="+examPaperID);
		}else{
			DS_QuesRecord record = new DS_QuesRecord();
			record.setExamPaperID(Integer.valueOf(examPaperID));
			record.setHaveDownNum(quesHavedoNum-1);
			record.setWrongNum(quesWrongNum);
			
			db.save(record);
		}
	}
	
	private int readHaveDoneQues(){
		FinalDb db = FinalDb.create(this, ConstAnts.BRKJ_DB);
		List<DS_QuesRecord> savedList = db.findAllByWhere(DS_QuesRecord.class, 
				" ExamPaperID=" + examPaperID); 
		
		if((savedList!=null) && (savedList.size()>0)){
			return savedList.get(0).getHaveDownNum();
		}else{
			return 0;
		}
	}

    private void showWrongQuesList(){
        Intent intent = new Intent(this, ExamWrongQuesActivity.class);
        intent.putExtra("examID", examPaperID);
        startActivity(intent);
    }

}
